package orm

import (
	"fmt"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// 实体之间外键关联: N v M
type Student struct {
	// 继承 gorm中的 Model
	gorm.Model

	Name string
	// autoCreateTime | autoUpdateTime 自动插入时间戳
	Version time.Time `gorm:"autoCreateTime"`

	// 生成中间表: stu_course
	Courses []Course `gorm:"many2many:stu_course"`
}

type Course struct {
	gorm.Model
	Name    string
	Teacher string
}

var db4 *gorm.DB

func init() {
	dsn := "root:root@tcp(localhost:3306)/go_db?charset=utf8mb4&parseTime=true"
	db1, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	db4 = db1
}

func main_10() {
	// 创建外键表
	db4.AutoMigrate(&Course{}, &Student{})
	insert2()

	student := selectAssociation2()
	fmt.Printf("student: %v\n", student)
}

func insert2() {
	// Create
	db4.Create(&Student{Name: "lisi",
		Courses: []Course{
			{Name: "英语", Teacher: "zhangsan"},
			{Name: "历史", Teacher: "易中天"},
		},
	})
}

// 关联查询
func selectAssociation2() Student {
	var student Student
	db4.First(&student)
	// fmt.Printf("student: %v\n", student)
	var courses []Course
	db4.Model(&student).Association("Courses").Find(&courses)
	// fmt.Printf("courses: %v\n", courses)
	student.Courses = courses
	return student
}
